export const BLUE_STATE = {
	/**
	 * 蓝牙不可用
	 */
	UNAVAILABLE: {
		label: '请检查手机蓝牙是否开启',
		code: -1
	},
	/**
	 * 等待连接蓝牙
	 */
	READY: {
		label: '等待连接蓝牙',
		code: 10000
	},
	/**
	 * 等待连接蓝牙(重启蓝牙适配器)
	 */
	READYAGAIN: {
		label: '等待连接蓝牙',
		code: 10001
	},
	/**
	 * 正在搜索设备...
	 */
	SCANING: {
		label: '正在搜索设备...',
		code: 12000
	},
	/**
	 * 正在传输数据...
	 */
	TRANSMITDATA: {
		label: '正在传输数据...',
		code: 13000
	},
	/**
	 * 数据传输完成
	 */
	LOCKDATA: {
		label: '数据已锁定',
		code: 11000
	},
	/**
	 * 已连接蓝牙
	 */
	CONNECTSUCCESS: {
		label: '已连接蓝牙',
		code: 200
	},
	/**
	 * 写入特征已准备就绪
	 */
	WRITEREADY: {
		label: '写入特征已准备就绪',
		code: 201
	},
	/**
	 * 蓝牙连接已断开
	 */
	DISCONNECT: {
		label: '蓝牙连接已断开',
		code: 500
	},
	/**
	 * 连接失败, 请重试！
	 */
	CONNECTFAILED: {
		label: '连接失败, 请重试！',
		code: -2
	},
	/**
	 * 微信无位置权限
	 */
	NOLOCATIONPERMISSION: {
		label: '您关闭了微信位置权限，请前往手机设置页打开权限后重试',
		code: 10007
	},
	/**
	 * 当前系统版本过低，请升级后重试！
	 */
	VERSIONLOW: {
		label: '当前系统版本过低，请升级后重试！',
		code: 10009
	},
	/**
	 * 系统异常，请稍后重试！
	 */
	SYSTEMERROR: {
		label: '系统异常，请稍后重试！',
		code: 10008
	}
}
export const Blue = {
	_isDiscovering: false, // 蓝牙适配器是否处于搜索状态
	bleConnectDeviceID: null, // 设备的 id
	callback: null,
	bleConnectStateCallBack(callback) {
		this.callback = callback
	},
	// 关闭蓝牙连接，关闭状态监听，初始化状态
	stop() {
		if (this.bleConnectDeviceID) {
			uni.closeBLEConnection({
				deviceId: this.bleConnectDeviceID
			})
		}
		this.bleConnectDeviceID = null
		this._isDiscovering = false
		uni.closeBluetoothAdapter()
		uni.offBluetoothAdapterStateChange()
		uni.offBLEConnectionStateChange()
		uni.stopBluetoothDevicesDiscovery()
	},
	start() {
		// 初始化蓝牙模块
		uni.openBluetoothAdapter({
			success: (res) => {
				console.log("11111 =======>>>>")
				// this.startBluetoothDevicesDiscovery()
			},
			fail: (res) => {
				console.error('打开蓝牙适配器失败：', res);
				this._isDiscovering = false
				if (res.errCode === 10001) {
					this.connectStateListen(BLUE_STATE.UNAVAILABLE)
				}
				// Android 系统特有，系统版本低于 4.3 不支持 BLE
				if(res.errCode === 10009) {
					this.connectStateListen(BLUE_STATE.VERSIONLOW)
				}
				if(res.errCode === 10008) {
					this.connectStateListen(BLUE_STATE.SYSTEMERROR)
				}
			},
			complete: () => {
				// 监听蓝牙适配器状态
				uni.onBluetoothAdapterStateChange(res => {
					console.log('蓝牙适配器状态：', res);
					if (res.available) {
						this._isDiscovering = res.discovering 
						this.connectStateListen(BLUE_STATE.READYAGAIN)
						this.startBluetoothDevicesDiscovery()
					}else {
						// 蓝牙模块未开启
						this.connectStateListen(BLUE_STATE.UNAVAILABLE)
					}
				})
			}
		})
	},
	// 开始蓝牙扫描
	startBluetoothDevicesDiscovery() {
		console.log("22222 =======>>>>")
		if (this._isDiscovering) return
		this._isDiscovering = true
		console.log("33333 =======>>>>")
		uni.startBluetoothDevicesDiscovery({
			allowDuplicatesKey: true, // 是否允许重复上报同一设备。
			success: (res) => {
				console.log("44444 =======>>>>", res)
				this.connectStateListen(BLUE_STATE.SCANING)
				this.onBluetoothDeviceFound()
			},
			fail: (res) => {
				if(res.errCode === -1 && (res.errno === 1509008 || res.errno === 1509009)) {
					this.stop()
					this.connectStateListen(BLUE_STATE.NOLOCATIONPERMISSION)
				}
			}
		})
	},
	// 搜索附近设备
	onBluetoothDeviceFound() {
		console.log("555555 =======>>>>")
		uni.onBluetoothDeviceFound(res => {
			console.log("6666666 =======>>>>", res)
			res.devices.forEach(device => {
				let abHex = this.ab2hex(device.advertisData)
				console.error(device.name, "这是什么鬼东西", abHex)
				// if() {
				// 	this.stopBluetoothDevicesDiscovery()
				// 	this.createBLEConnection(device)
				// }
				
			})
		})
	},
	// 停止蓝牙扫描
	stopBluetoothDevicesDiscovery() {
		uni.stopBluetoothDevicesDiscovery({
		  success(res) {
			console.log("停止蓝牙扫描====",res)
		  }
		})
	},
	// 创建蓝牙连接
	createBLEConnection(device) {
		console.log("创建蓝牙连接", device)
		console.log(this.bleConnectDeviceID)
		if (this.bleConnectDeviceID == null) {
			this.bleConnectDeviceID = device.deviceId
			uni.createBLEConnection({
				deviceId: device.deviceId,
				success: res=> {
					console.log("7777777 =======>>>>", res)
					// currentDevice = device
					this.connectState = 200
					// 蓝牙连接成功，上报设备信息
					this.connectStateListen({
						...BLUE_STATE.CONNECTSUCCESS,
						deviceInfo: {...device}
					})
					this.getBLEDeviceServices(device)
					this.onBLEConnectionStateChange()
				},
				fail: (err)=> {
					this.connectStateListen(BLUE_STATE.CONNECTFAILED)
				},
			})
		}
	},
	// 监听连接状态
	onBLEConnectionStateChange() {
		uni.onBLEConnectionStateChange(res => {
			console.log('++++++蓝牙连接状态: ', res);
			if (!res.connected) {
				this.connectStateListen(BLUE_STATE.DISCONNECT)
				this.stop()
			}
		});
	},
	// 获取设备服务
	getBLEDeviceServices(device) {
		uni.getBLEDeviceServices({
			deviceId: device.deviceId,
			success: res=> {
				console.log("8888888 =======>>>>", res)
				for (let i = 0; i < res.services.length; i++) {
					let uuid = res.services[i].uuid
					if (uuid.indexOf("FFF0") == 0) {
						this.getBLEDeviceCharacteristics(device, uuid)
					}
				}
			},
		})
	},
	// 获取设备特征值
	getBLEDeviceCharacteristics(device, serviceID) {
		console.log("获取设备特征值 =======>>>>", res)
		uni.getBLEDeviceCharacteristics({
			deviceId: device.deviceId,
			serviceId: serviceID,
			success: res=> {
				for (let i = 0; i < res.characteristics.length; i++) {
					let item = res.characteristics[i]
					// 该特征值是否支持 write 操作
					if (item.properties.write) { 
						if (item.uuid.indexOf("FFF1") == 0) {
							let writeData = {
								device: device, 
								serviceID: serviceID,
								characteristicID: item.uuid
							}
							this.connectStateListen(BLUE_STATE.WRITEREADY);
						}
					}
					// 该特征值是否支持 notify或indicate 操作
					if (item.properties.notify || item.properties.indicate) { 
						if (item.uuid.indexOf("FFF4") == 0) {
							this.notifyBLECharacteristicValueChange(device, serviceID, item.uuid);
						}
					}
				}
			}
		})
	},
	// 监听特征值变化（设备数据变化）
	notifyBLECharacteristicValueChange(device, serviceID, characteristicID) {
		console.log("监听特征值变化 =======>>>>", res)
		uni.notifyBLECharacteristicValueChange({
			deviceId: device.deviceId,
			serviceId: serviceID,
			characteristicId: characteristicID,
			state: true,
			success: res=> {
				this.onBLECharacteristicValueChange()
			},
		})
	},
	onBLECharacteristicValueChange() {
		uni.onBLECharacteristicValueChange(res=> {
			let value = this.ab2hex(res.value)
			this.resolvingData(value)
		})
	},
	connectStateListen(data) {
		console.log("=======>>>> ",data)
		this.callback(data)
	},
	// ArrayBuffer转16进制字符串
	ab2hex(buffer, split='') {
		var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		})
		return hexArr.join(split)
	},
	
	// TODO 根据自己实际业务解析数据
	resolvingData(res) {
		console.log('啊哈哈哈哈哈哈')
		if (this._lastLockData == res) return
		this._lastLockData = res
	},
}